package com.yige.web.controller

import com.mongodb.DBObject
import com.yige.common.MD5Util
import com.yige.common.ResultUtil
import com.yige.common.SystemConstant
import com.yige.service.mongoService.MongoResourceService
import com.yige.service.mongoService.MongoRoleService
import com.yige.service.mongoService.MongoUserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody

import javax.servlet.http.HttpSession

/**
 * Created by sunhao on 2015/9/17 0017.
 */


@Controller
@RequestMapping("login")
class LoginController {

    @Autowired
    MongoUserService userService
    @Autowired
    MongoRoleService roleService
    @Autowired
    MongoResourceService resourceService

    /*************控制器模块************/

    /**
     * 用户登录
     * @param username
     * @param password
     * @param httpSession
     * @return
     */
    @RequestMapping("login")
    def login(String username, String password, HttpSession httpSession,Model model){
        // 校验用户名和密码
        Map<String, Object> map = checkUser(username, password)
        if(map == null){
            return "login"
        }
        int flag = Integer.valueOf(map.get("flag").toString())
        if (flag == SystemConstant.SUCCESS) {
            // 登录成功
            // 将登录信息存入session,将用户权限资源存入model
            DBObject user = (DBObject) map.get("user")
            user.http = "jsp"
            List<DBObject> menu = findUserMenu(user)
            List<String> auth = new ArrayList<>(userService.findUserAuth(user))
            httpSession.setAttribute("user", user)
            httpSession.setAttribute("auth",auth)
            model.addAttribute("user",user)
            model.addAttribute("flag",flag)
            model.addAttribute("menu",menu)
            return "index"
        } else {
            // 登录失败
            if(flag == SystemConstant.USER_NAME_ERROR){
                model.addAttribute("msg",flag)
            }else if (flag == SystemConstant.PASSWORD_ERROR){
                model.addAttribute("msg",flag)
            }
            return "login"
        }
    }

    /**
     * 用户登出
     * @param session
     * @return
     */
    @RequestMapping("logout")
    def logout(HttpSession session){
        //注销session
        session.invalidate();
        return "login";
    }

    @RequestMapping("updatePwd")
    @ResponseBody
    def updatePwd(HttpSession session, String lastPwd, String newPwd){
        DBObject user = (DBObject) session.getAttribute("user")
        boolean flag = userService.updatePwd(user,lastPwd,newPwd)
        return ResultUtil.recallAjax(flag)
    }



    /*****************方法模块*****************/


    /**
     * 查询用户拥有资源菜单
     * @param user
     * @return
     */
    def findUserMenu(DBObject user) {
        List<DBObject> roleList = new ArrayList<>(user.role),
                       resourceList = new LinkedList<>()
        def menuList = new ArrayList()
        Map parent = new HashMap()
        DBObject role_db,resource_db
        roleList.each { info ->
            role_db = roleService.findOneById(info)
            for(int i=0; i<role_db.resource.size(); i++){
                resource_db = resourceService.findOneById(role_db.resource[i])
                if(SystemConstant.RESOURCE_TYPE_NAV.equals(resource_db.type)){
                    parent.put(resource_db.group,resource_db.name)
                }
                if(SystemConstant.RESOURCE_TYPE_MENU.equals(resource_db.type)){
                    resourceList.add(resource_db)
                }
            }
        }
        parent.each {pa->
            def childList = new LinkedList()
            resourceList.each {resource->
                if(pa.getKey() == resource.group){
                    childList.add(resource)
                }
            }
            menuList.add(["name":pa.getValue(),"children":childList])
        }
        return menuList
    }

    /**
     * 检查用户名和密码
     * @param username
     * @param password
     * @return
     */
    def checkUser(String username, String password) {
        if (username == null)
            throw new RuntimeException("用户名不能为空.")
        if (password == null)
            throw new RuntimeException("密码不能为空.")
        Map<String, Object> map = new HashMap<String, Object>()

        // 校验用户名是否正确
        DBObject user_db = userService.findUserByName(username)
        if(user_db == null){
            return
        }
        if (user_db.status == SystemConstant.USER_OFF_JOB){
            //用户被禁止
            map.put("flag",SystemConstant.USER_STATUS_OFF)
            return map
        }
        if (user_db == null) {
            // 用户名不存在
            map.put("flag", SystemConstant.USER_NAME_ERROR)
            return map
        }

        // 需要对加密后的密码进行比较
        String md5Password = MD5Util.md5(password)
        if (!md5Password.equals(user_db.password)) {
            map.put("flag", SystemConstant.PASSWORD_ERROR)
            return map
        }

        // 校验成功
        map.put("flag", SystemConstant.SUCCESS)
        map.put("user", user_db)
        return map
    }
}

